package com.example.finaltool.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class TimeUtils {

    private static final BigDecimal milliUnit = new BigDecimal("1000");

    public static String duration(LocalDateTime start) {
        return duration(start, LocalDateTime.now());
    }

    public static String duration(LocalDateTime start, LocalDateTime end) {
        return adjustTime(durationInMillis(start, end));
    }

    private static long durationInMillis(LocalDateTime start, LocalDateTime end) {
        return ChronoUnit.MILLIS.between(start, end);
    }

    private static String adjustTime(long milli) {
        BigDecimal duration = new BigDecimal(milli);
        if (duration.compareTo(milliUnit) > 0) {
            return duration.divide(milliUnit, 1, RoundingMode.HALF_DOWN) + "s";
        } else {
            return duration + "ms";
        }
    }
}
